package com.batchengine.cron;

import static com.batchengine.Definitions.DataAdapter.FILE;
import static com.batchengine.cron.ScheduledJobParser.getCronDataParser;
import com.batchengine.task.ScheduledJob;

import static java.lang.System.currentTimeMillis;
import java.util.ArrayList;
import java.util.Calendar;
import static java.util.Calendar.getInstance;
import java.util.Collection;
import java.util.Date;

/**
 * User: sunil.incubator@yahoo.com
 * Date: Sep 29, 2009
 * Time: 4:28:31 PM
 */
public class CronManagerUtil {

    public static Collection<ScheduledJob> loadCronData() {
        ScheduledJobParser parser = getCronDataParser(FILE);
        return parser.loadData();
    }

    public static Collection<ScheduledJob> getAllScheduledTasksForNextHour(final long nxtHr) {

        Collection<ScheduledJob> cronList = new ArrayList<ScheduledJob>();
        try {

            Collection<ScheduledJob> cronCollection = loadCronData();
            CronParser parser = new CronParser();

            long crnHr = currentTimeMillis();
            for (ScheduledJob data : cronCollection) {
                parser.setCronExpression(data.getExpression());
                long prsHr = parser.getTimeBefore(nxtHr);
                data.setScheduledTime(new Date(prsHr));
                if (prsHr >= crnHr && prsHr <= nxtHr) {
                    cronList.add(data);
                }
            }
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
        return cronList;
    }

    public static long getNextHour() {
        Calendar c = getInstance();
        c.set(Calendar.HOUR, c.get(Calendar.HOUR) + 1);
        return c.getTimeInMillis();
    }
}
